import axios from 'axios';
import iview from 'iview';
import store from '../store/';
import router from '../router/'

// 导入封装的回调函数
import { gbs } from '../config/settings.js';


// axios 配置
axios.defaults.timeout = 30000;
axios.defaults.baseURL = gbs.host;
axios.defaults.withCredentials = true;
// http request 拦截器
axios.interceptors.request.use(
    config => {
        iview.LoadingBar.start();
        if (store.getters.getToken) {
            config.headers.Authorization = `Bearer ${store.getters.getToken}`;
        }
        // store.dispatch('show_loading').then(() => {
        //     console.log("---------------------");
        // });
        return config;
    },
    err => {
        return Promise.reject(err);
    });

// http response 拦截器
axios.interceptors.response.use(
    response => {
        iview.LoadingBar.finish();
        // store.dispatch('hide_loading').then(() => {
        //     console.log("---------------------");
        // });
        if (!response.config.hideTip) {
            if (response.data.errorCode != 0) {
                if (response.data.message) {
                    iview.Message.error({
                        content: response.data.message,
                        duration: 5,
                        closable: true
                    });

                }
            }
        }

        return response.data;
    },
    error => {
        iview.LoadingBar.error();
        if (error.response) {
            switch (error.response.status) {
                case 500:
                    iview.Message.error("服务器异常")
                    break;
                case 504:
                    iview.Message.error("网络错误")
                    break;
                case 401: // 401 清除token信息并跳转到登录页面
                    store.dispatch('remove_userinfo').then(() => {
                        iview.Message.error('请登录！');
                        router.replace({
                            path: '/login',
                            query: { redirect: router.currentRoute.fullPath }
                        })
                    });
                    break;
                case 403: // 403 清除token信息并跳转到登录页面
                    iview.Message.error({
                        content: '您没有权限访问该页面！',
                        duration: 2
                    });
                    //router.replace('/');
                    break;
                default:
                    iview.Message.error('请求错误！');
            }
        } else {
            iview.Message.error('网络错误！');
        }

        // console.log(JSON.stringify(error)); //console : Error: Request failed with status code 402
        return Promise.reject(error);
    }
);

export default axios;